﻿using StackExchange.Redis;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;
using CHSystemApi.Framework.Extension;

namespace CHSystemApi.Framework.Redis
{
    public class Redis : IRedis
    {
        private ConnectionMultiplexer _redis;

        private IDatabase _database;

        public Redis(ConnectionMultiplexer redis)
        {
            _redis = redis;

            _database = _redis.GetDatabase(1);
        }

        public bool Exist(string key)
        {
            return _database.KeyExists(key);
        }

        public string Get(string key)
        {
            return _database.StringGet(key).ToString();
        }

        public T Get<T>(string key)
        {
            string result = _database.StringGet(key).ToString();
            if (string.IsNullOrEmpty(result))
                return default(T);
            return JsonConvert.DeserializeObject<T>(result);
        }

        public bool Remove(string key)
        {
            return _database.KeyDelete(key);
        }

        public bool Set(string key, object value, TimeSpan expiry)
        {
            return _database.StringSet(new RedisKey(key), new RedisValue(JsonConvert.SerializeObject(value)), expiry);
        }

        public IRedis ChangeDataBase(RedisDataBaseType type)
        {
            _database = _redis.GetDatabase((int)type);
            return this;
        }
    }
}
